package com.eqxiu.ieditor.api.controller.weixin;

import java.net.URLEncoder;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.eqxiu.ieditor.api.controller.BaseApiController;
import com.eqxiu.ieditor.api.controller.weixin.doc.WxDoc;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.ieditor.weixin.api.WeiXinServiceApi;
import com.eqxiu.ieditor.weixin.dto.JsTicket;
import com.eqxiu.ieditor.weixin.dto.QrTicket;

@RestController
public class WxController implements WxDoc, BaseApiController {

	private Logger logger = LoggerFactory.getLogger(WxController.class);

	@Autowired
	private WeiXinServiceApi weiXinServiceApi;


	@GetMapping("/api/wx/get-qrticket")
	public ResultData getQRTicket(@RequestParam String appId, @RequestParam String sceneCode) {
		try {
			QrTicket ticket = weiXinServiceApi.getLimitTicket(appId, sceneCode);
			//Optional<QrTicketDTO> ticket = weiXinServiceApi.getLimitTicket(appId, sceneCode);
			return ResultData.result(true).setObj(URLEncoder.encode(ticket.getTicket(), "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
			return ResultData.result(false).setMsg(e.getMessage());
		}
	}

	@GetMapping("/api/wx/get-jsticket")
	public ResultData getJSTicket(@RequestParam String appId, @RequestParam(defaultValue = "jsapi") String type) {
		try {
			JsTicket ticket = weiXinServiceApi.getJsTicket(appId, type);
			//Optional<JsTicketDTO> ticket = weiXinServiceApi.getJsTicket(appId, type);
//			if (!ticket.isPresent()) {
//				// try again
//				ticket = weiXinServiceApi.getJsTicket(appId, type);
//				if (!ticket.isPresent()) {
//					return ResultData.result(false).setMsg("get ticket is null!");
//				}
//			}
			if (ticket == null) {
				ticket = weiXinServiceApi.getJsTicket(appId, type);
				if (ticket == null) {
					return ResultData.result(false).setMsg("get ticket is null!");
				}
			}
			return ResultData.result(true).setObj(URLEncoder.encode(ticket.getTicket(), "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
			return fail().setMsg(e.getMessage());
		}
	}

	@PostMapping("/api/wx/signJsApi")
	public ResultData signJsApi(@RequestParam String appId, @RequestParam String url) {
		Map result = weiXinServiceApi.signJsApi(appId, url);
		return success().setMap(result);
	}

}
